import SwiftUI
import PhotosUI

struct PhotoPickerView: View {
    @State private var selectedItems: [PhotosPickerItem] = []
    @State private var selectedImages: [UIImage] = []
    @State private var showingEditView = false
    @State private var currentImageIndex = 0
    @State private var isLoading = false
    @Environment(\.dismiss) private var dismiss
    
    var body: some View {
        NavigationStack {
            ZStack {
                Color.black.ignoresSafeArea()
                
                VStack(spacing: StyleConstants.Spacing.lg) {
                    if selectedImages.isEmpty {
                        emptyStateView
                    } else {
                        selectedImagesView
                    }
                }
            }
            .navigationTitle("Choose Photos")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    Button("Cancel") {
                        dismiss()
                    }
                    .foregroundColor(.white)
                }
                
                if !selectedImages.isEmpty {
                    ToolbarItem(placement: .navigationBarTrailing) {
                        Button("Edit") {
                            showingEditView = true
                        }
                        .foregroundColor(.white)
                        .fontWeight(.semibold)
                    }
                }
            }
        }
        .onChange(of: selectedItems) { _, newItems in
            loadImages(from: newItems)
        }
        .fullScreenCover(isPresented: $showingEditView) {
            if !selectedImages.isEmpty {
                ProfessionalEditView(image: selectedImages[currentImageIndex])
            }
        }
        .preferredColorScheme(.dark)
    }
    
    // MARK: - Empty State View
    
    private var emptyStateView: some View {
        VStack(spacing: StyleConstants.Spacing.xl) {
            Spacer()
            
            // Icon
            ZStack {
                Circle()
                    .fill(Color.white.opacity(0.1))
                    .frame(width: 120, height: 120)
                
                Image(systemName: "photo.on.rectangle.angled")
                    .font(.system(size: 48, weight: .light))
                    .foregroundColor(.white.opacity(0.8))
            }
            .breathingEffect()
            
            // Text content
            VStack(spacing: StyleConstants.Spacing.sm) {
                Text("Choose Your Photos")
                    .font(StyleConstants.Typography.title2)
                    .fontWeight(.semibold)
                    .foregroundColor(.white)
                
                Text("Select photos from your library to apply professional filters")
                    .font(StyleConstants.Typography.body)
                    .foregroundColor(.white.opacity(0.7))
                    .multilineTextAlignment(.center)
                    .padding(.horizontal, StyleConstants.Spacing.lg)
            }
            
            Spacer()
            
            // Photo picker button
            PhotosPicker(
                selection: $selectedItems,
                maxSelectionCount: 10,
                matching: .images
            ) {
                HStack(spacing: StyleConstants.Spacing.sm) {
                    Image(systemName: "plus.circle.fill")
                        .font(.system(size: 20))
                    
                    Text("Select Photos")
                        .font(StyleConstants.Typography.bodyEmphasized)
                }
                .frame(maxWidth: .infinity)
                .frame(height: 56)
                .background(
                    LinearGradient(
                        gradient: Gradient(colors: [
                            Color.white,
                            Color.white.opacity(0.9)
                        ]),
                        startPoint: .topLeading,
                        endPoint: .bottomTrailing
                    )
                )
                .foregroundColor(.black)
                .cornerRadius(StyleConstants.Layout.cornerRadius)
                .shadow(color: .white.opacity(0.3), radius: 8, x: 0, y: 4)
            }
            .pressableStyle()
            .padding(.horizontal, StyleConstants.Spacing.lg)
            
            // Feature highlights
            HStack(spacing: StyleConstants.Spacing.xl) {
                FeatureHighlight(
                    icon: "wand.and.rays",
                    text: "AI Enhanced"
                )
                
                FeatureHighlight(
                    icon: "speedometer",
                    text: "Fast Processing"
                )
                
                FeatureHighlight(
                    icon: "square.and.arrow.up",
                    text: "Easy Share"
                )
            }
            .padding(.horizontal, StyleConstants.Spacing.lg)
            
            Spacer()
        }
        .padding(StyleConstants.Spacing.lg)
    }
    
    // MARK: - Selected Images View
    
    private var selectedImagesView: some View {
        VStack(spacing: StyleConstants.Spacing.lg) {
            // Main image preview
            if isLoading {
                loadingView
            } else {
                mainImagePreview
            }
            
            // Image selection strip
            if selectedImages.count > 1 {
                imageSelectionStrip
            }
            
            // Action buttons
            actionButtons
        }
        .padding(StyleConstants.Spacing.lg)
    }
    
    private var loadingView: some View {
        VStack(spacing: StyleConstants.Spacing.md) {
            ProgressView()
                .progressViewStyle(CircularProgressViewStyle(tint: .white))
                .scaleEffect(1.5)
            
            Text("Loading photos...")
                .font(StyleConstants.Typography.body)
                .foregroundColor(.white.opacity(0.8))
        }
        .frame(height: 300)
        .frame(maxWidth: .infinity)
        .background(Color.white.opacity(0.1))
        .cornerRadius(StyleConstants.Layout.cornerRadius)
    }
    
    private var mainImagePreview: some View {
        GeometryReader { geometry in
            if !selectedImages.isEmpty {
                Image(uiImage: selectedImages[currentImageIndex])
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .frame(maxWidth: geometry.size.width, maxHeight: geometry.size.height)
                    .cornerRadius(StyleConstants.Layout.cornerRadius)
                    .clipped()
                    .shadow(color: .black.opacity(0.3), radius: 8, x: 0, y: 4)
            }
        }
        .frame(height: 400)
        .background(Color.white.opacity(0.05))
        .cornerRadius(StyleConstants.Layout.cornerRadius)
    }
    
    private var imageSelectionStrip: some View {
        ScrollView(.horizontal, showsIndicators: false) {
            HStack(spacing: StyleConstants.Spacing.sm) {
                ForEach(Array(selectedImages.enumerated()), id: \.offset) { index, image in
                    Button(action: {
                        withAnimation(StyleConstants.Animation.quick) {
                            currentImageIndex = index
                        }
                    }) {
                        Image(uiImage: image)
                            .resizable()
                            .aspectRatio(contentMode: .fill)
                            .frame(width: 60, height: 60)
                            .cornerRadius(StyleConstants.Layout.smallCornerRadius)
                            .clipped()
                            .overlay(
                                RoundedRectangle(cornerRadius: StyleConstants.Layout.smallCornerRadius)
                                    .stroke(
                                        index == currentImageIndex ? Color.white : Color.clear,
                                        lineWidth: 2
                                    )
                            )
                            .scaleEffect(index == currentImageIndex ? 1.1 : 1.0)
                            .shadow(
                                color: index == currentImageIndex ? .white.opacity(0.3) : .clear,
                                radius: 4,
                                x: 0,
                                y: 0
                            )
                    }
                    .pressableStyle()
                }
            }
            .padding(.horizontal, StyleConstants.Spacing.lg)
        }
        .frame(height: 80)
    }
    
    private var actionButtons: some View {
        HStack(spacing: StyleConstants.Spacing.md) {
            // Add more photos
            PhotosPicker(
                selection: $selectedItems,
                maxSelectionCount: 10,
                matching: .images
            ) {
                HStack(spacing: StyleConstants.Spacing.xs) {
                    Image(systemName: "plus")
                        .font(.system(size: 16, weight: .medium))
                    
                    Text("Add More")
                        .font(StyleConstants.Typography.callout)
                }
                .frame(maxWidth: .infinity)
                .frame(height: 44)
                .background(Color.white.opacity(0.1))
                .foregroundColor(.white.opacity(0.8))
                .cornerRadius(StyleConstants.Layout.smallCornerRadius)
                .overlay(
                    RoundedRectangle(cornerRadius: StyleConstants.Layout.smallCornerRadius)
                        .stroke(Color.white.opacity(0.3), lineWidth: 1)
                )
            }
            .pressableStyle()
            
            // Edit current photo
            Button(action: {
                showingEditView = true
            }) {
                HStack(spacing: StyleConstants.Spacing.xs) {
                    Image(systemName: "slider.horizontal.3")
                        .font(.system(size: 16, weight: .medium))
                    
                    Text("Edit Photo")
                        .font(StyleConstants.Typography.callout)
                        .fontWeight(.semibold)
                }
                .frame(maxWidth: .infinity)
                .frame(height: 44)
                .background(Color.white)
                .foregroundColor(.black)
                .cornerRadius(StyleConstants.Layout.smallCornerRadius)
                .shadow(color: .white.opacity(0.3), radius: 4, x: 0, y: 2)
            }
            .pressableStyle()
        }
    }
    
    // MARK: - Helper Functions
    
    private func loadImages(from items: [PhotosPickerItem]) {
        isLoading = true
        selectedImages = []
        
        let group = DispatchGroup()
        var loadedImages: [(Int, UIImage)] = []
        
        for (index, item) in items.enumerated() {
            group.enter()
            
            item.loadTransferable(type: Data.self) { result in
                defer { group.leave() }
                
                switch result {
                case .success(let data):
                    if let data = data, let image = UIImage(data: data) {
                        loadedImages.append((index, image))
                    }
                case .failure(let error):
                    print("Failed to load image: \(error)")
                }
            }
        }
        
        group.notify(queue: .main) {
            // Sort by original order
            loadedImages.sort { $0.0 < $1.0 }
            selectedImages = loadedImages.map { $0.1 }
            currentImageIndex = 0
            isLoading = false
            
            // Add haptic feedback
            HapticFeedback.light()
        }
    }
}

// MARK: - Feature Highlight Component

struct FeatureHighlight: View {
    let icon: String
    let text: String
    
    var body: some View {
        VStack(spacing: StyleConstants.Spacing.xs) {
            Image(systemName: icon)
                .font(.system(size: 20, weight: .medium))
                .foregroundColor(.white.opacity(0.8))
            
            Text(text)
                .font(StyleConstants.Typography.caption)
                .foregroundColor(.white.opacity(0.6))
        }
    }
}

#Preview {
    PhotoPickerView()
        .preferredColorScheme(.dark)
}